package com.jiuxian.scheduling.controller;

import com.jiuxian.scheduling.commons.ErrorType;
import com.jiuxian.scheduling.commons.LogInfoContext;
import com.jiuxian.scheduling.commons.ResponseEntity;
import com.jiuxian.scheduling.config.ConfigServer;
import com.jiuxian.scheduling.config.ConfigServerFactory;
import com.jiuxian.scheduling.servers.LogServer;
import com.jiuxian.scheduling.tasks.SchedulerApplication;
import com.jiuxian.scheduling.util.SiteUtil;
import com.jiuxian.scheduling.vo.LogInfoVO;
import com.jiuxian.scheduling.vo.SchedingVO;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.*;

/**
 * Created by wangjingqing on 2017/11/9.
 */
@Controller
@RequestMapping("/scheduling")
public class SchedulingController {

    Logger logger = LoggerFactory.getLogger(SchedulingController.class);

    private ConfigServer configServer = ConfigServerFactory.getConfigServer();

    @Autowired
    private LogServer logServer;
    /**
     * 查询列表
     * @return
     */
    @ResponseBody
    @RequestMapping("/list")
    public Object getList(){
        List<Map<String,Object>> reDate = new ArrayList<>();
        List<SchedingVO> schedingList = configServer.getAll();
        if(CollectionUtils.isNotEmpty(schedingList)){
            schedingList.forEach(info->{
                Map<String,Object> data = new HashMap<>();
                data.put("name",info.getName());
                data.put("path",info.getPath());
                data.put("cron",info.getCron());
                data.put("stateTitle",info.getState() == 0 ? "执行中":info.getState() == 1? "暂停":info.getState()== 2 ?"恢复":"删除");
                data.put("state",info.getState());
                reDate.add(data);
            });
        }
        return ResponseEntity.seccuess(reDate);
    }

    /**
     * 添加
     * @param request HttpServletRequest
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/add",method = {RequestMethod.POST,RequestMethod.GET})
    public Object add(HttpServletRequest request){
        String name = request.getParameter("name");
        if(StringUtils.isBlank(name)){
            return ResponseEntity.error(ErrorType.parameter_error);
        }

        String path = request.getParameter("path");
        if(StringUtils.isBlank(path)){
            return ResponseEntity.error(ErrorType.parameter_error);
        }

        String method = request.getParameter("method");
        if(StringUtils.isBlank(method)){
            return ResponseEntity.error(ErrorType.parameter_error);
        }
        String cron = request.getParameter("cron");
        if(StringUtils.isBlank(cron)){
            return ResponseEntity.error(ErrorType.parameter_error);
        }
        String protocol = request.getParameter("protocol");
        if(StringUtils.isBlank(protocol)){
            return ResponseEntity.error(ErrorType.parameter_error);
        }
        //注册路径和版本号
        String url = null;
        String version = null;
        if("dubbo".equalsIgnoreCase(protocol)){
            //注册路径
            url = request.getParameter("url");
            if(StringUtils.isBlank(url)){
                return ResponseEntity.error(ErrorType.parameter_error);
            }
            version = request.getParameter("version");
            if(StringUtils.isBlank(version)){
                return ResponseEntity.error(ErrorType.parameter_error);
            }
        }
        String group = null;
        if(!"local".equalsIgnoreCase(protocol)){
            group = request.getParameter("group");
            if(StringUtils.isBlank(group)){
                return ResponseEntity.error(ErrorType.parameter_error);
            }
        }

        SchedingVO schedingVO = new SchedingVO(name,url,path,method,cron);
        schedingVO.setGroup(group);
        schedingVO.setStartTime(new Date());
        schedingVO.setVersion(version);
        String parameters = request.getParameter("parameters");
        if(StringUtils.isBlank(parameters)){
            schedingVO.setParameters("");
        }else{
            schedingVO.setParameters(parameters);
        }
        schedingVO.addMachine(SiteUtil.getRequestIp(request),1);
        schedingVO.setState(0);
        schedingVO.setStartTime(new Date());
        schedingVO.setProtocol(protocol);
        schedingVO.setNextDate(SiteUtil.getDate(new Date(),10));
        configServer.add(schedingVO);
        SchedulerApplication.addJob(schedingVO);
        return ResponseEntity.seccuess("");
    }

    /**
     * 查看信息<br>
     * @param name 名称
     * @return
     */
    @ResponseBody
    @RequestMapping("/show")
    public Object show(@RequestParam(name="name",defaultValue = "") String name){
        if(StringUtils.isBlank(name)){
            return ResponseEntity.error(ErrorType.parameter_error);
        }
        SchedingVO schedingVO = configServer.get(name);
        return ResponseEntity.seccuess(schedingVO);
    }

    /**
     * 删除
     * @param name 名称
     * @return
     */
    @ResponseBody
    @RequestMapping("/delete")
    public Object delete(@RequestParam(name="name",defaultValue = "") String name){
        configServer.delete(name);
        SchedulerApplication.removeJob(name);
        return ResponseEntity.seccuess("");
    }

    /**
     * 暂停
     * @param name 名称
     * @param state 状态 0：运行 1：暂停
     * @return
     */
    @ResponseBody
    @RequestMapping("/changeSate")
    public Object changeSate(@RequestParam(name="name",defaultValue = "") String name,@RequestParam(name="state",defaultValue = "0") Integer state){
        SchedingVO data = configServer.get(name);
        if(data != null){
            data.setChange(true);
            if(data.getNextDate() == null || data.getNextDate().compareTo(new Date()) < 1){
                data.setNextDate(SiteUtil.getDate(new Date(),10));
            }
            data.setState(state);
            configServer.update(data);
        }
        if(state == 0){//运行
            SchedulerApplication.addJob(data);
        }else{
            SchedulerApplication.removeJob(name);
        }
        return ResponseEntity.seccuess("");
    }

    /**
     * 获取错误信息<br/>
     * @return
     */
    @ResponseBody
    @RequestMapping("/errorInfo")
    public Object errorInfo(){
        //查询10条错误信息
        List<LogInfoVO> errorList = LogInfoContext.errorList(5);
        return ResponseEntity.seccuess(errorList);
    }

    /**
     * 获取错误信息<br/>
     * @return
     */
    @ResponseBody
    @RequestMapping("/infos")
    public Object infos(HttpServletRequest request){
        List<LogInfoVO> infos = logServer.selectLogInfos(request.getParameter("name"), null, null);
        List<Map<String,Object>> reDate = new ArrayList<>();
        if(CollectionUtils.isNotEmpty(infos)){
            infos.forEach(info->{
                Map<String,Object> data = new HashMap<>();
                data.put("name",info.getName());
                data.put("taskTime",info.getTaskTime());
                data.put("creatTime",info.getCreatTime());
                data.put("state",info.getState()?"成功":"失败");
                String details = info.getDetails();
                if(StringUtils.isNotBlank(details)){
                    String[] detailsArray = details.split("\r\n");
                    data.put("details",Arrays.asList(detailsArray));
                }
                reDate.add(data);
            });
        }
        return ResponseEntity.seccuess(reDate);
    }
}
